class Solution:
    @staticmethod
    def minTime(n: int, edges: list[list[int]], hasApple: list[bool]) -> int:
        # 边表转图
        tree = [[] for _ in range(n)]
        for edge in edges:
            tree[edge[0]].append(edge[1])
            tree[edge[1]].append(edge[0])

        # 图转父亲树
        fatherTree = [-1 for _ in range(n)]
        # 层序队列
        queue = [0]
        for i in queue:
            for edge in tree[i]:
                # 跳过父亲
                if edge == fatherTree[i]:
                    continue

                fatherTree[edge] = i
                queue.append(edge)

        del tree
        del queue
        # 记录关键路径
        criticalPath = set()

        # 关键路径寻找
        for i in range(n):
            # 不是苹果就下一个
            if hasApple[i] is False:
                continue

            # 回根路径记录
            j = i
            while j != 0:
                path = (fatherTree[j], j) if fatherTree[j] < j else (j, fatherTree[j])
                # 若路径已被记录，则此处到根的路径一定被记录
                if path in criticalPath:
                    break
                # 记录
                criticalPath.add(path)
                # 下一个
                j = fatherTree[j]

        return len(criticalPath) << 1
